package com.liaoban.app.ui;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.liaoban.app.R;
import com.liaoban.app.api.type.event.AutoInstallEvent;
import com.liaoban.app.api.type.event.DownloadEvent;
import com.liaoban.app.api.type.request.ImSendGiftReq;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.constants.ConfigKey;
import com.liaoban.app.helper.ConfigHelper;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.base.BaseActivity;
import com.liaoban.app.ui.follow.FollowFragment;
import com.liaoban.app.ui.home.HomeFragment;
import com.liaoban.app.ui.login.LoginActivity;
import com.liaoban.app.ui.message.MessageFragment;
import com.liaoban.app.ui.message.MyAVChatActivity;
import com.liaoban.app.ui.message.MyP2PMessageActivity;
import com.liaoban.app.ui.mine.MineFragment;
import com.liaoban.app.ui.mine.RechargeActivity;
import com.liaoban.app.ui.rank.RankFragment;
import com.liaoban.app.update.UpdateHelper;
import com.liaoban.app.util.CommonUtils;
import com.netease.neliveplayer.sdk.NEDynamicLoadingConfig;
import com.netease.neliveplayer.sdk.NELivePlayer;
import com.netease.neliveplayer.sdk.NESDKConfig;
import com.netease.nim.avchatkit.AVChatProfile;
import com.netease.nim.avchatkit.activity.AVChatActivity;
import com.netease.nim.avchatkit.constant.AVChatExtras;
import com.netease.nim.avchatkit.event.AvChatEvent;
import com.netease.nim.avchatkit.event.ChongZhiEvent;
import com.netease.nim.demo.session.SessionHelper;
import com.netease.nim.uikit.event.P2PMessageEvent;
import com.netease.nim.uikit.event.SendGiftEvent;
import com.netease.nim.uikit.support.permission.MPermission;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionDenied;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionGranted;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionNeverAskAgain;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.NimIntent;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;

public class MainActivity extends BaseActivity {
    private static final int BASIC_PERMISSION_REQUEST_CODE = 100;
    private static final int INSTALL_APK_REQUESTCODE = 101;
    private static final int GET_UNKNOWN_APP_SOURCES = 102;

    @BindView(android.R.id.tabs)
    TabWidget tabs;
    @BindView(android.R.id.tabhost)
    FragmentTabHost mTabHost;

    private TextView tvMsgCount;
    private ProgressDialog mDownloadPd;
    private File mApkFile;

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setNeedOnBus(true);
        onParseIntent();
        initTabHost();
        requestBasicPermission();
        checkPublishPermission(); //点播权限
        checkUmeng(); //友盟权限
        initNeLivePlay();
        int unreadNum = NIMClient.getService(MsgService.class).getTotalUnreadCount();
        setMsgCount(unreadNum);

        String registrationId = CommonUtils.getRegistrationID(this); //激光推送
        Log.e("ybc", "registrationId:" + registrationId);
        silentCheckUpdate();
    }

    private void initTabHost() {
        mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.tab_home)).setIndicator(getIndicator(R.string.tab_home, R.drawable.ic_home, false)),
                HomeFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.tab_rank)).setIndicator(getIndicator(R.string.tab_rank, R.drawable.ic_rank, false)),
                RankFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.tab_attention)).setIndicator(getIndicator(R.string.tab_attention, R.drawable.ic_attention, false)),
                FollowFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.tab_msg)).setIndicator(getIndicator(R.string.tab_msg, R.drawable.ic_msg, true)),
                MessageFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec(getString(R.string.tab_mine)).setIndicator(getIndicator(R.string.tab_mine, R.drawable.ic_mine, false)),
                MineFragment.class, null);
        changeLogin(2);
        changeLogin(3);
        changeLogin(4);
    }

    private void silentCheckUpdate() {
        // 延时一点，等首页数据加载完再检查新版本
        Observable.timer(3, TimeUnit.SECONDS).subscribe(aLong -> {
            UpdateHelper.getInstance().doUpdateCheckRequest(this, false);
        });
    }

    /**
     * 需要登录判断
     *
     * @param index
     */
    private void changeLogin(int index) {
        mTabHost.getTabWidget().getChildTabViewAt(index).setOnClickListener(view -> {
            if (CommonBiz.getInstance().isLogin(MainActivity.this)) {
                changeTab(index);
            } else {
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            }
        });
    }


    //tab item_recharge 项控件
    private View getIndicator(int text, int imgId, boolean isMsg) {
        View view = getLayoutInflater().inflate(R.layout.item_bottom_tab, null);
        ((TextView) view.findViewById(R.id.tv_tab_name)).setText(text);
        ((ImageView) view.findViewById(R.id.iv_icon)).setImageResource(imgId);
        if (isMsg) {
            tvMsgCount = view.findViewById(R.id.tv_msg_count);
        }
        return view;
    }

    /**
     * 根据坐标来切换fragment
     *
     * @param index
     */
    public void changeTab(int index) {
        mTabHost.setCurrentTab(index);
    }

    /**
     * 设置消息数量
     *
     * @param count
     */
    public void setMsgCount(int count) {
        if (count > 0) {
            tvMsgCount.setText(String.valueOf(count));
            tvMsgCount.setVisibility(View.VISIBLE);
        } else {
            tvMsgCount.setVisibility(View.GONE);
        }
    }

    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    private void requestBasicPermission() {
        MPermission.printMPermissionResult(true, this, BASIC_PERMISSIONS);
        MPermission.with(MainActivity.this)
                .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        switch (requestCode) {
            case WRITE_PERMISSION_REQ_CODE:
                for (int ret : grantResults) {
                    if (ret != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                }
                break;
            case 123:// 友盟权限没有同意的相应操作
                break;
            case INSTALL_APK_REQUESTCODE:
                //有注册权限且用户允许安装
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    autoInstall(mApkFile);
                } else {
                    //将用户引导至安装未知应用界面。
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
                    ToastHelper.show(this, "设置中，请打开允许安装未知应用");
                }
                break;
            case GET_UNKNOWN_APP_SOURCES:
                autoInstallEvent();
                break;
            default:
                break;
        }
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
        try {
            Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        try {
            Toast.makeText(this, "未全部授权，部分功能可能无法正常运行！", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    private final int WRITE_PERMISSION_REQ_CODE = 100;

    private boolean checkPublishPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE)) {
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        (String[]) permissions.toArray(new String[0]),
                        WRITE_PERMISSION_REQ_CODE);
                return false;
            }
        }
        return true;
    }

    private void initNeLivePlay() {
        NESDKConfig config = new NESDKConfig();
        //动态加载
        config.dynamicLoadingConfig = new NEDynamicLoadingConfig();
        //是否开启动态加载功能，默认关闭
//		config.dynamicLoadingConfig.isDynamicLoading = true;
        config.dynamicLoadingConfig.isArmeabi = true;
       /* config.dynamicLoadingConfig.onDynamicLoadingListener = mOnDynamicLoadingListener;
        config.supportDecodeListener = mOnSupportDecodeListener;
        //SDK将内部的网络请求以回调的方式开给上层，如果需要上层自己进行网络请求请实现config.dataUploadListener，如果上层不需要自己进行网络请求而是让SDK进行网络请求，这里就不需要操作config.dataUploadListener
        config.dataUploadListener =  mOnDataUploadListener;*/
        NELivePlayer.init(this, config);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onP2PMessageEvent(P2PMessageEvent p2PMessageEvent) {
        startActivity(MyP2PMessageActivity.newIntent(this, p2PMessageEvent.contactId, p2PMessageEvent.customization, p2PMessageEvent.anchor));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSendGiftEvent(SendGiftEvent sendGiftEvent) {
        String tel = ConfigHelper.getString(this, ConfigKey.USER_TEL);
        ImSendGiftReq imSendGiftReq = new ImSendGiftReq();
        imSendGiftReq.setId(String.valueOf(sendGiftEvent.position + 1));
        imSendGiftReq.setFuser_im_id(tel);
        imSendGiftReq.setWuser_im_id(sendGiftEvent.container.account);
        startTask(CommonBiz.getInstance().imSendGift(imSendGiftReq), integerBaseResponse -> {
            ToastHelper.show(this, integerBaseResponse.msg);
            if (integerBaseResponse.code == 1) {
                ConfigHelper.save(MainActivity.this, ConfigKey.USER_LIAO_MONEY, String.valueOf(integerBaseResponse.data));
                String item = "gift00" + (sendGiftEvent.position + 1);
                MsgAttachment attachment = sendGiftEvent.customization.createStickerAttachment("gift", item);
                IMMessage stickerMessage = MessageBuilder.createCustomMessage(sendGiftEvent.container.account, sendGiftEvent.container.sessionType, "贴图消息", attachment);
                sendGiftEvent.container.proxy.sendMessage(stickerMessage);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAvChatEvent(AvChatEvent avChatEvent) {
        avChatEvent.intent.setClass(this, MyAVChatActivity.class);
        startActivity(avChatEvent.intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChongZhiEvent(ChongZhiEvent chongZhiEvent) {
        startActivity(new Intent(this, RechargeActivity.class));
    }

    private void checkUmeng() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDownloadEvent(DownloadEvent downloadEvent) {
        Intent intent = new Intent(this, MainActivity.class);
        //Log.e("yubch", "MainActivity is Top:" + CommonUtils.isTop(this, intent));
        if (CommonUtils.isTop(this, intent)) {
            showDownloadPd(downloadEvent.mProgress);
        }
    }

    /**
     * 下载进度条
     *
     * @param progress
     */
    private void showDownloadPd(int progress) {
        if (mDownloadPd == null) {
            mDownloadPd = new ProgressDialog(this);
            mDownloadPd.setTitle("正在下载...");
            mDownloadPd.setCanceledOnTouchOutside(true);
            mDownloadPd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mDownloadPd.setMax(100);
        }
        tabs.post(() -> mDownloadPd.setProgress(progress));
        if (progress < 100) {
            mDownloadPd.show();
        } else {
            mDownloadPd.dismiss();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAutoInstallEvent(AutoInstallEvent autoInstallEvent) {
        Intent intent = new Intent(this, MainActivity.class);
        if (CommonUtils.isTop(this, intent)) {
            mApkFile = autoInstallEvent.mApkFile;
            autoInstallEvent();
        }
    }

    private void autoInstallEvent() {
        if (Build.VERSION.SDK_INT >= 26) { //8.0
            //来判断应用是否有权限安装apk
            boolean installAllowed = getPackageManager().canRequestPackageInstalls();
            //有权限
            if (installAllowed) {
                //安装apk
                autoInstall(mApkFile);
            } else {
                //无权限 申请权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_APK_REQUESTCODE);
            }
        } else {
            autoInstall(mApkFile);
        }
    }

    private void autoInstall(File apkFile) {
        /*String type = "application/vnd.android.package-archive";
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(mApkFile), type);
        startActivity(intent);*/
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        // 判断版本大于等于7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
            data = FileProvider.getUriForFile(this, "com.liaoban.app.fileprovider", apkFile);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            data = Uri.fromFile(apkFile);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        onParseIntent();
    }

    private void onParseIntent() {
        Log.e("yubch", "onParseIntent()");
        Intent intent = getIntent();
        if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)) {
            IMMessage message = (IMMessage) getIntent().getSerializableExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
            switch (message.getSessionType()) {
                case P2P:
                    SessionHelper.startP2PSession(this, message.getSessionId());
                    break;
                case Team:
                    SessionHelper.startTeamSession(this, message.getSessionId());
                    break;
                default:
                    break;
            }
        } else if (intent.hasExtra(AVChatActivity.INTENT_ACTION_AVCHAT)) {
            Log.e("yubch", "isAVChatting()");
            if (AVChatProfile.getInstance().isAVChatting()) {
                Intent localIntent = new Intent();
                localIntent.setClass(this, AVChatActivity.class);
                startActivity(localIntent);
            }
        } else if (intent.hasExtra(AVChatExtras.EXTRA_FROM_NOTIFICATION)) {
            Log.e("yubch", "EXTRA_ACCOUNT");
            String account = intent.getStringExtra(AVChatExtras.EXTRA_ACCOUNT);
            if (!TextUtils.isEmpty(account)) {
                SessionHelper.startP2PSession(this, account);
            }
        }
    }
}
